import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
  Form,
  Checkbox,
  Radio,
  Input,
  Row,
  Button,
  Table,
  Col,
  Select,
  Space,
  message,
} from 'antd';
import { connect } from 'react-redux';
import { nanoid } from 'nanoid';
import {
  add_template,
  change_default,
  update_template,
} from '../../../../store/actions/order';

function TemplateCom(props) {
  const { add_template, change_default, update_template } = props;
  const location = useLocation();
  const { state } = location;
  // const isDefault = state.isDefault;
  // delete state.isDefault;
  // console.log(state);
  // console.log(location);
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [value, setValue] = useState(0);
  const areaOpt = [
    {
      value: 1,
      label: '北京、天津、河北、山东',
    },
    {
      value: 2,
      label: '辽宁、吉林、黑龙江',
    },
    {
      value: 3,
      label: '成都、重庆',
    },
    {
      value: 4,
      label: '上海、浙江、江苏',
    },
    {
      value: 5,
      label: '青海、甘肃',
    },
    {
      value: 6,
      label: '云南、贵州',
    },
  ];
  const columns = [
    {
      title: '可配送区域',
      dataIndex: 'distributeArea',
      key: 'distributeArea',
      render: () => (
        <Form.Item required name='distributeArea'>
          <Select
            labelInValue
            onChange={areaChange}
            style={{
              width: 180,
            }}
            options={areaOpt}
            placeholder='请选择'
          />
        </Form.Item>
      ),
    },
    {
      // title: state ? (state.priceType === 0 ? '首件（个）' : '首重（KG）') : value === 0 ? '首件（个）' : '首重（KG）',
      title: state
        ? state.priceType === 0
          ? '首件（个）'
          : '首重（KG）'
        : value === 0
        ? '首件（个）'
        : '首重（KG）',
      dataIndex: 'firstWeight',
      key: 'firstWeight',
      render: () => (
        <Form.Item required name='firstPiece'>
          <Input
            type='text'
            placeholder='请输入'
            style={{
              width: 80,
            }}
          />
        </Form.Item>
      ),
    },
    {
      title: '运费（元）',
      dataIndex: 'unitFeeW',
      key: 'unitFeeW',
      render: () => (
        <Form.Item required name='unitFee'>
          <Input
            type='text'
            placeholder='请输入'
            style={{
              width: 80,
            }}
          />
        </Form.Item>
      ),
    },
    {
      title: state
        ? state.priceType === 0
          ? '续件（个）'
          : '续重（KG）'
        : value === 0
        ? '续件（个）'
        : '续重（KG）',
      dataIndex: 'addWeight',
      key: 'addWeight',
      render: () => (
        <Form.Item required name='addPiece'>
          <Input
            type='text'
            placeholder='请输入'
            style={{
              width: 80,
            }}
          />
        </Form.Item>
      ),
    },
    {
      title: '续费（元）',
      dataIndex: 'addFeeW',
      key: 'addFeeW',
      render: () => (
        <Form.Item required name='addFee'>
          <Input
            type='text'
            placeholder='请输入'
            style={{
              width: 80,
            }}
          />
        </Form.Item>
      ),
    },
    {
      title: '操作',
      key: 'id',
      render: el => (
        <Button type='link button' id={el.id}>
          删除
        </Button>
      ),
    },
  ];
  const tableData = [{ key: 1 }];
  // 根据计价方式 修改表格内容
  const onPriceType = e => {
    setValue(e.target.value);
  };
  // 格式化时间
  function formatDateTime(date) {
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    let d = date.getDate();
    d = d < 10 ? '0' + d : d;
    let h = date.getHours();
    h = h < 10 ? '0' + h : h;
    let min = date.getMinutes();
    min = min < 10 ? '0' + min : min;
    let sec = date.getSeconds();
    sec = sec < 10 ? '0' + sec : sec;
    return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + sec;
  }
  // 获取下拉框的label值
  let distributeArea = '';
  const areaChange = (v, e) => {
    distributeArea = v.label;
  };
  let timer = null;
  const onSubmit = () => {
    const {
      priceType,
      name,
      firstPiece,
      unitFee,
      addPiece,
      addFee,
      isDefault,
      distributeArea,
    } = form.getFieldValue();
    // console.log(form.getFieldValue());
    let content = '';
    // 收集数据
    let newTemp = {};
    if (priceType === 0) {
      newTemp.firstPiece = firstPiece * 1;
      newTemp.unitFee = unitFee * 1;
      newTemp.addPiece = addPiece * 1;
      newTemp.addFee = addFee * 1;
    } else {
      newTemp.firstWeight = firstPiece * 1;
      newTemp.unitFeeW = unitFee * 1;
      newTemp.addWeight = addPiece * 1;
      newTemp.addFeeW = addFee * 1;
    }
    newTemp = {
      name,
      isDefault,
      updateTime: formatDateTime(new Date()),
      distributeArea: distributeArea.label,
      priceType: priceType === 0 ? '按件数' : '按重量',
      relatedGoodsNum: 1,
      ...newTemp,
    };
    if (state) {
      // 编辑
      if (isDefault) {
        update_template({ id: state.id, newState: newTemp });
        // 修改默认
        change_default(state.id);
      } else {
        update_template({ id: state.id, newState: newTemp });
      }
      content = '修改成功';
    } else {
      // 新增
      newTemp.id = nanoid();
      // 设置默认模板
      if (isDefault) {
        // 新增
        add_template(newTemp);
        // 修改默认
        change_default(newTemp.id);
      } else {
        // 新增
        add_template(newTemp);
      }
      content = '添加成功';
    }
    messageApi.open({
      type: 'success',
      content,
      duration: 1,
    });
    timer = setTimeout(() => {
      navigate('/home/distribution-management');
    }, 1000);
  };
  const cancel = () => {
    navigate('/home/distribution-management');
  };
  const initialValues = state
    ? {
        ...state,
        priceType: state.priceType === '按件数' ? 0 : 1,
        distributeArea: {
          value: areaOpt.filter(el => el.label === state.distributeArea)[0]
            .value,
          label: state.distributeArea,
        },
        firstPiece: state.firstPiece || state.firstWeight,
        unitFee: state.unitFee || state.unitFeeW,
        addPiece: state.addPiece || state.addWeight,
        addFee: state.addFee || state.addFeeW,
      }
    : { priceType: 0, isDefault: false };
  useEffect(
    () => () => {
      clearTimeout(timer);
    },
    [timer]
  );
  return (
    <>
      {contextHolder}
      <Form
        form={form}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 14,
        }}
        layout='horizontal'
        initialValues={initialValues}>
        <Form.Item label='模板名称' required name='name'>
          <Input type='text' placeholder='请输入' style={{ width: 250 }} />
        </Form.Item>
        <Form.Item label='计价方式' required name='priceType'>
          <Radio.Group onChange={onPriceType} value={value}>
            <Radio value={0}>按件数</Radio>
            <Radio value={1}>按重量</Radio>
          </Radio.Group>
        </Form.Item>
        <Row>
          <Col push={4} span={20}>
            <Table
              columns={columns}
              dataSource={tableData}
              pagination={false}
            />
          </Col>
        </Row>
        <Row>
          <Col push={4} span={20}>
            <Form.Item name='isDefault' valuePropName='checked'>
              <Checkbox>设为默认模板</Checkbox>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col push={18} span={6}>
            <Form.Item>
              <Space size={15}>
                <Button type='primary button' onClick={onSubmit}>
                  确定
                </Button>
                <Button type='default button' onClick={cancel}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </>
  );
}

export default connect(state => ({ state: state.templateReducer }), {
  add_template,
  change_default,
  update_template,
})(TemplateCom);
